package com.bojiu.lawsearch.lawsearch.controller;

import com.bojiu.lawsearch.lawsearch.form.AppChangeEngineerForm;
import com.bojiu.lawsearch.lawsearch.form.AppTaskMarkingForm;
import com.bojiu.lawsearch.lawsearch.model.LawBaseInfo;
import com.bojiu.lawsearch.lawsearch.model.Page;
import com.bojiu.lawsearch.lawsearch.model.Task;
import com.bojiu.lawsearch.lawsearch.service.TaskService;
import com.bojiu.lawsearch.lawsearch.util.AuthorizationHandle;
import com.bojiu.lawsearch.lawsearch.util.JsonResult;
import com.bojiu.lawsearch.lawsearch.util.ResultCode;
import com.bojiu.lawsearch.lawsearch.util.UtilTools;
import com.bojiu.lawsearch.lawsearch.wxzf.WXZFService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author: afdiao
 * @Date：2020/4/5 15:20
 * @Description:用户提问相关
 */
@Api(description = "发布任务以及充值接口")
@RestController
@RequestMapping("task")
@Slf4j
public class TaskController {

    @Autowired
    TaskService taskService;

    @Autowired
    WXZFService wxzfService;

    @Autowired
    AuthorizationHandle authorizationHandle;

    /**
     * 发布任务
     *
     * @param task
     * @param errors
     * @param request
     * @return
     */
    @ApiOperation(value = "提问", notes = "用户提问，最fuck的功能！！！")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = LawBaseInfo.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 2000, message = "不是会员，请开通会员使用")
    })
    @PostMapping("publish")
    public JsonResult publish(@ApiParam(name = "任务对象明细", value = "json格式", required = true) @Valid @RequestBody Task task, Errors errors, HttpServletRequest request) {
        if (errors.hasErrors()) {
            return UtilTools.handleNullField(errors);
        }
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        if (!authorizationHandle.memberHandle(userId, true)) {
            log.error("还不是会员，无法查询");
            return new JsonResult(ResultCode.NO_MEMBER);
        }
        //获取用户id
        JsonResult publish = taskService.publish(task, userId, request);
        return publish;
    }

    @ApiOperation(value = "校验任务是否支付", notes = "校验任务是否支付成功")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = LawBaseInfo.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 2000, message = "不是会员，请开通会员使用"),
            @ApiResponse(code = 2300, message = "尚未支付")
    })
    @GetMapping("checkPay/{taskId}")
    public JsonResult checkPay(@ApiParam(name = "taskId", value = "任务id", required = true)@PathVariable("taskId") int taskId,HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        if (!authorizationHandle.memberHandle(userId, true)) {
            log.error("还不是会员，无法查询");
            return new JsonResult(ResultCode.NO_MEMBER);
        }
        JsonResult result = taskService.checkPay(taskId, userId);
        return result;
    }


    /**
     * 微信开通会员
     *
     * @return
     */
    @ApiOperation(value = "开通会员", notes = "开通会员，返回微信支付的二维码Base64")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = String.class),
    })
    @GetMapping("memberPay/{goodsId}")
    public JsonResult memberPay(@ApiParam(name = "goodsId", value = "微信会员商品的id", required = true) @PathVariable("goodsId") int goodsId, HttpServletRequest request) {
        //判断用户权限
        JsonResult jsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(jsonResult.getCode())) {
            log.error("审核没有通过");
            return jsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(jsonResult.getData()));
        JsonResult result = taskService.memberPay(goodsId, request, userId);
        return result;
    }

    @PostMapping("refund")
    public JsonResult refund(@RequestBody String string) {
        String orderNum = new Gson().fromJson(string, JsonObject.class).get("orderNum").getAsString();
        int fee = new Gson().fromJson(string, JsonObject.class).get("fee").getAsInt();
        JsonResult refund = wxzfService.refund(orderNum, fee, fee);
        return refund;
    }

    /**
     * 查看已发布的任务
     *
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @ApiOperation(value = "查看已发布的任务", notes = "查看已发布的任务")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Task.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @GetMapping("myTask/{pageNum}/{pageSize}")
    public JsonResult myTask(@ApiParam(name = "pageNum", value = "当前页码", required = true) @PathVariable("pageNum") int pageNum, @ApiParam(name = "pageSize", value = "每页个数", required = true) @PathVariable("pageSize") int pageSize, HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        Page<Task> task = taskService.geMyTask(userId, pageSize, pageNum);
        return new JsonResult(ResultCode.SUCCESS, task);
    }

    /**
     * 给工程师打分
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "给工程师打分", notes = "给工程师打分")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Task.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("marking")
    public JsonResult marking(@Valid @RequestBody AppTaskMarkingForm form, HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        Task task = taskService.queryById(form.getTaskId());
        if (!task.getUserId().equals(userId)) {
            log.info("无法给其他人发布的任务评分");
            return new JsonResult(ResultCode.FAIL);
        }
        return taskService.marking(task, form.getStar());
    }


    /**
     * 更换工程师
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "更换工程师", notes = "更换工程师")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Task.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
            @ApiResponse(code = 500, message = "没有权限访问该接口")
    })
    @PostMapping("changeEngineer")
    public JsonResult changeEngineer(@Valid @RequestBody  AppChangeEngineerForm form, HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        Task task = taskService.queryById(form.getTaskId());
        if (!task.getUserId().equals(userId)) {
            log.info("无法给其他人发布的任务更换工程师");
            return new JsonResult(ResultCode.FAIL);
        }
        return taskService.changeEngineer(task);
    }
}
